package com.wyz.web.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyz.common.dto.UserDTO;
import com.wyz.common.po.UserPO;
import com.wyz.web.mapper.UserRepository;
import com.wyz.web.service.UserService;
import com.wyz.common.util.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private DataSourceTransactionManager transactionManager;


    /**
     * 原生方式完成编程式事务
     */
    public boolean transfer(int sender_id, int receiver_id, double money) {
        TransactionStatus status = transactionManager.getTransaction(transactionTemplate);

        try {
            userRepository.updateAsset(sender_id, -money);
            int i = 1 / 0;
            userRepository.updateAsset(receiver_id, money);
            transactionManager.commit(status);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            status.setRollbackOnly();
            transactionManager.commit(status);
            return false;
        }

    }

    @Override
    public String addUser(UserDTO userDTO) {
        // 判断用户名是否存在
        UserPO userPO = userRepository.selectOne(new QueryWrapper<UserPO>().lambda().eq(UserPO::getUsername, userDTO.getUsername()));
        if (userPO != null) {
            return "该用户名已经注册";
        } else {
            // 在数据库中加一个用户
            UserPO u = new UserPO();
            u.setUsername(userDTO.getUsername());
            u.setPassword(userDTO.getPassword());
            u.setPhone(userDTO.getPhone());
            userRepository.insert(u);
        }
        return "success";
    }


    @Override
    public String checkUserInfo(UserDTO userDTO) {

        Message msg = new Message();
        UserPO userPO = userRepository.selectOne(new QueryWrapper<UserPO>().eq("username", userDTO.getUsername())); //判断用户名是否存在

        if (userPO == null) {
//            msg.setFlag(-1);
//            msg.setMsg("用户不存在");
            return "用户不存在";
        } else if (userDTO.getPassword()==null || !userDTO.getPassword().equals(userPO.getPassword())) {
//            msg.setFlag(-2);
//            msg.setMsg("密码不正确");
            return "密码不正确";
        }
//            msg.setFlag(1);
//            msg.setMsg("登录成功");
        return "success";
    }
}
